package com.boss.salary.utils;

import com.boss.salary.vo.ComparisonResultVo;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * <br>Title:比较类
 * <br>Description:
 * <br>Author:
 * <br>Date:
 */
public class CompareUtils {

    /**
     * 比较两个相同对象的值
     * @param beforeObj
     * @param afterObj
     * @return
     * @throws Exception
     */
    public static List<ComparisonResultVo> compareObj(Object beforeObj, Object afterObj) throws Exception{
        List<ComparisonResultVo> differents = new ArrayList<ComparisonResultVo>();

        if(beforeObj == null) {
            throw new Exception("原对象不能为空");
        }
        if(afterObj == null) {
            throw new Exception("新对象不能为空");
        }
        if(!beforeObj.getClass().isAssignableFrom(afterObj.getClass())){
            throw new Exception("两个对象不相同，无法比较");
        }
        //取出属性
        Field[] beforeFields = beforeObj.getClass().getDeclaredFields();
        Field[] afterFields = afterObj.getClass().getDeclaredFields();
        Field.setAccessible(beforeFields, true);
        Field.setAccessible(afterFields, true);

        //遍历取出差异值
        if(beforeFields != null && beforeFields.length > 0){
            for(int i=0; i<beforeFields.length; i++){
                Object beforeValue = beforeFields[i].get(beforeObj);
                Object afterValue = afterFields[i].get(afterObj);
                if((!StringUtils.isEmpty(beforeValue) && !beforeValue.equals(afterValue)) ||
                        ((StringUtils.isEmpty(beforeValue) && !StringUtils.isEmpty(afterValue)))){
                    ComparisonResultVo comparison = new ComparisonResultVo();
                    comparison.setField(beforeFields[i].getName());
                    comparison.setBefore(beforeValue);
                    comparison.setAfter(afterValue);
                    differents.add(comparison);
                }
            }
        }
        return differents;
    }
}
